<template>
  <div class="grammar-container">
    <el-row :gutter="20" style="height: 99%;">
      <el-col :span="6" class="grammar-sidebar">
        <el-input v-model="searchText" placeholder="搜索语法..." clearable class="search-input">
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>
        <el-scrollbar class="grammar-list">
          <el-menu :default-active="activeGrammar" @select="handleSelectGrammar" class="grammar-menu">
            <el-sub-menu v-for="group in filteredGrammarList" :key="group.id" :index="group.filename">
              <template #title>
                <div class="grammar-group-item">
                  <span>
                    <el-icon v-if="group.items && group.items.length > 0">
                      <Folder />
                    </el-icon>
                    <span>{{ group.id }}.{{ group.groupName }}</span>
                  </span>
                  <el-button text class="grammar-group-link" @click="loadGroup(group)" @click.stop>
                    查看
                  </el-button>
                </div>
              </template>
              <el-menu-item v-for="item in group.items" :key="item.filename" :index="item.filename">
                {{ item.title }}
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-scrollbar>
      </el-col>
      <el-col :span="18" class="grammar-content">
        <div v-if="loading" class="loading">
          <el-skeleton :rows="10" animated />
        </div>
        <div v-else-if="activeGrammarContent" class="content">
          <h2>{{ activeGrammarTitle }}</h2>
          <div v-if="!isText()" class="grammar-text" v-html="renderMarkdown(activeGrammarContent)"></div>
          <pre v-else-if="isText()">{{ (activeGrammarContent) }}</pre>
        </div>
        <div v-else class="empty">
          <el-empty description="请选择一个语法项查看内容" />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import http from '@/utils/http';
import { ref, onMounted, computed, watch } from 'vue'
import { Search, Folder } from '@element-plus/icons-vue'
import { ElRow, ElCol, ElInput, ElScrollbar, ElMenu, ElMenuItem, ElSkeleton, ElEmpty, ElIcon } from 'element-plus'
import { marked } from 'marked'

export default {
  name: 'Grammar',
  components: {
    ElRow,
    ElCol,
    ElInput,
    ElScrollbar,
    ElMenu,
    ElMenuItem,
    ElSkeleton,
    ElEmpty,
    ElIcon,
    Search,
    Folder
  },
  setup() {
    const searchText = ref('')
    const grammarList = ref([])
    const activeGrammar = ref('')
    const activeGrammarContent = ref('')
    const activeGrammarTitle = ref('')
    const loading = ref(false)
    const format = ref("markdown")

    // 获取语法列表
    const fetchGrammarList = async () => {
      try {
        const response = await http.get('/grammar')
        const data = response
        grammarList.value = data
        if (data.length > 0 && !activeGrammar.value) {
          // 默认选中第一个
          handleSelectGrammar(data[0].filename)
        }
      } catch (error) {
        console.error('获取语法列表失败:', error)
      }
    }

    // 获取语法内容
    const fetchGrammarContent = async (filename) => {
      loading.value = true
      try {
        // 请求markdown格式的内容
        const response = await http.get(`/grammar/${filename}?format=${format.value}`)
        const data = response
        activeGrammarContent.value = data.content
        activeGrammarTitle.value = data.title
      } catch (error) {
        console.error('获取语法内容失败:', error)
        activeGrammarContent.value = ''
        activeGrammarTitle.value = ''
      } finally {
        loading.value = false
      }
    }

    // 处理选择语法项
    const handleSelectGrammar = (filename) => {
      activeGrammar.value = filename
      fetchGrammarContent(filename)
    }
    const loadGroup = (group) => {
      activeGrammar.value = group.filename;
      fetchGrammarContent(group.filename);
    }
    const isText = () => {
      return format.value === 'text';
    }
    // 渲染Markdown内容
    const renderMarkdown = (content) => {
      if (!content) return ''
      if (format.value === 'text') return content;
      return marked(content)
    }

    // 过滤语法列表
    const filteredGrammarList = computed(() => {
      if (!searchText.value) {
        return grammarList.value
      }

      const search = searchText.value.toLowerCase();
      let newList = grammarList.value.map(g => {
        return { ...g };
      });
      newList = newList.filter(g =>
        g.filename.toLowerCase().includes(search) ||
        g.items.filter(i => {
          return i.title.toLowerCase().includes(search)
        }).length > 0
      );
      newList = [...newList];
      for (let i = 0; i < newList.length; i++) {
        const g = newList[i];
        let filterItems = g.items;
        filterItems = filterItems.filter(i => {
          return i.title.toLowerCase().includes(search)
        });
        newList[i].items = filterItems;
      }
      return newList;
    })

    // 监听搜索文本变化
    watch(searchText, () => {
      if (filteredGrammarList.value.length > 0 &&
        !filteredGrammarList.value.some(item => item.filename === activeGrammar.value)) {
        // 如果当前选中的项不在搜索结果中，则选中第一个
        handleSelectGrammar(filteredGrammarList.value[0].filename)
      }
    })

    onMounted(() => {
      fetchGrammarList()
    })

    return {
      searchText,
      grammarList,
      activeGrammar,
      activeGrammarContent,
      activeGrammarTitle,
      loading,
      filteredGrammarList,
      handleSelectGrammar,
      loadGroup,
      renderMarkdown, isText
    }
  }
}
</script>

<style scoped>
.grammar-container {
  height: calc(100vh - 80px);
  overflow: hidden;
}

.grammar-group-link {
  padding: auto;
}

.grammar-group-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.grammar-sidebar {
  height: 100%;
  display: flex !important;
  flex-direction: column;
}

.search-input {
  margin-bottom: 15px;
}

.grammar-list {
  flex: 1;
}

.grammar-menu {
  border-right: none;
}

.grammar-content {
  height: 100%;
  overflow: auto;
}

.content {
  padding: 20px;
}

.content h2 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.grammar-text {
  font-family: 'DynaPuff light';
  line-height: 1.8;
  font-size: 16px;
}

.grammar-text :deep(h1),
.grammar-text :deep(h2),
.grammar-text :deep(h3) {
  margin: 16px 0 8px 0;
}

.grammar-text :deep(ul) {
  padding-left: 20px;
}

.grammar-text :deep(li) {
  margin: 8px 0;
}

.grammar-text :deep(p) {
  margin: 8px 0;
}

.loading,
.empty {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>